#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import logger
from Utils.Timer import timer
from Src.ScriptExcelParser import ScriptExcelParser


class NonDirectSellSkins(ScriptExcelParser):
    """解析 非直售皮肤.xlsx"""
    @timer(tracer=False)
    def load_data(self):
        """
        遍历"非直售皮肤.xlsx"的Data表，读取配置项和值
        :return: dict组装的list
        """
        ws = self.workbook['Data']
        data_list = list()
        section_len = slice(1, 11)
        section_height = 2
        init_row = 1

        for cur_row in range(init_row, ws.max_row + 1, section_height + 1):
            title = [x.value for x in (ws[init_row][section_len])]
            val = [x.value for x in (ws[init_row + 1][section_len])]
            if val[0]:
                data_dict = dict(map(lambda k, v: (k, v), title, val))
                data_list.append(data_dict)
            else:
                break
            init_row += section_height + 1

        if data_list:
            logger.info('读取工作簿[{0}]工作表[{1}]成功'.format(self.file_name, 'Data'))
        else:
            logger.warning('读取工作簿[{0}]工作表[{1}]结果为空'.format(self.file_name, 'Data'))

        return data_list

    def refactor_data(self, item_id, data_dict):
        """
        重构 非直售皮肤.xlsx 的配置值，将其拼装成适合配置表的格式
        :param item_id: 物品id，从配置表中进行读取
        :param data_dict: 配置项和配置值组成的dict
        :return: 重构后的dict
        """
        refactor_dict = dict()
        refactor_dict['>>XPath'] = xpath_dict['Objects_Data']
        refactor_dict['ID'] = item_id
        _skin_type_list = self.load_config()['skin_type']
        _skin_type_dict = list(filter(lambda d: d['皮肤类型'] == data_dict['皮肤类型'], _skin_type_list))[0]
        _skin_type_num = int(_skin_type_dict['皮肤类型编号'])
        refactor_dict['Type'] = _skin_type_num
        refactor_dict['Zprice'] = data_dict['棒棒糖价值']
        refactor_dict['autosell'] = "0:1"
        refactor_dict['Validtime'] = 0
        refactor_dict['Commentary'] = "{0}-{1}".format(data_dict['皮肤类型'], data_dict['皮肤名称'])
        _zprice, zshow = data_dict['棒棒糖价值'], data_dict['Show值']
        if _zprice and zshow:
            _sell = int(max(data_dict['棒棒糖价值'] * 0.1, data_dict['Show值'] * 0.3))
        elif _zprice and not zshow:
            _sell = int(data_dict['棒棒糖价值'] * 0.1)
        elif not _zprice and zshow:
            _sell = int(data_dict['Show值'] * 0.3)
        else:
            raise ValueError('"棒棒糖价值"和"Show值"不能同时为空')

        refactor_dict['sell'] = "1014:{0}".format(_sell)
        refactor_dict['show'] = data_dict['Show值']
        refactor_dict['tlifepower'] = data_dict['钛金护盾']
        # 过滤dict中的空值
        refactor_dict = dict(map(lambda t: (t[0], t[1]), filter(lambda t: t[1] is not None, refactor_dict.items())))

        if refactor_dict:
            logger.info('重构工作簿[{0}]工作表[{1}]配置项[{2}]成功'.format(self.file_name, 'Data', refactor_dict))
        else:
            logger.warning('重构工作簿[{0}]工作表[{1}]结果为空'.format(self.file_name, 'Data'))

        return refactor_dict


def non_direct_sell_skins(script_excel_path, config_excel_obj):
    """
    读取"非直售皮肤.xlsx"的填写内容，将配置项拼装成合适的数据结构，
    搜索相应的配置表，找到具体的工作表名和行，
    插入"非直售皮肤.xlsx"固定的工作表，以供赋值粘贴"
    :param script_excel_path: 表格"非直售皮肤.xlsx"的路径
    :param config_excel_obj: ConfigExcelParser类初始化配置表后生成的对象，可以直接调用ConfigExcelParser的方法
    :return: None
    """
    script_excel_name = script_excel_path.split('/')[-1]
    script_excel_obj = NonDirectSellSkins(script_excel_path)
    data_list = script_excel_obj.load_data()
    setting_dict = script_excel_obj.load_config()
    skin_type_list = setting_dict['skin_type']

    if data_list:
        c_row = 1
        for data_dict in data_list:

            skin_type_dict = list(filter(lambda d: d['皮肤类型'] == data_dict['皮肤类型'], skin_type_list))[0]
            sheet_name = skin_type_dict['SheetName']
            item_xpath = xpath_dict['Objects_Data']
            search_result = config_excel_obj.sr_title_nonadjacent(xpath=item_xpath, title='ID', sheet_name=sheet_name)

            item_id = search_result['ID'] - 1
            item_row_num = search_result['RowNum']
            title_list = config_excel_obj.get_column_titles(sheet_names=[sheet_name])[sheet_name][0]
            title_list.insert(0, 'SheetName')
            title_list.insert(1, 'RowNum')
            refactor_dict = script_excel_obj.refactor_data(item_id, data_dict)
            refactor_dict['SheetName'] = sheet_name
            refactor_dict['RowNum'] = item_row_num

            script_excel_obj.insert_output(c_row, title_list, refactor_dict)
            c_row += 3

        script_excel_obj.save_workbook()
    else:
        logger.warning('工作表[{0}]中没有填写配置数据'.format(script_excel_name))


if __name__ == '__main__':
    from Config.PackPath import SCRIPT_EXCEL_DIR
    import os
    path = os.path.join(SCRIPT_EXCEL_DIR, '非直售皮肤.xlsx')
    excel = NonDirectSellSkins(path)
    datalist = excel.load_data()
    print(datalist)
    for datadict in datalist:
        refdict = excel.refactor_data(None, datadict)
        print(refdict)
